package com.whereta.service.impl;

import com.github.pagehelper.PageInfo;
import com.whereta.dao.ILoginLogDao;
import com.whereta.model.LoginLog;
import com.whereta.service.ILogService;
import com.whereta.vo.ResultVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by vincent on 15-9-12.
 */
@Service("logService")
public class LogServiceImpl implements ILogService {
    @Resource
    private ILoginLogDao loginLogDao;

    /**
     * 查询登录日志
     *
     * @param page
     * @param count
     * @return
     */
    @Override
    public ResultVO queryLoginLog(int page, int count) {
        ResultVO resultVO = new ResultVO(true);
        PageInfo<LoginLog> pageInfo = loginLogDao.query(page, count);
        Map<String, Object> dataMap = new HashMap<>();
        List<LoginLog> list = pageInfo.getList();
        for (LoginLog loginLog : list) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            loginLog.setShowLoginTime(format.format(loginLog.getLoginTime()));
        }
        dataMap.put("rows", list);
        dataMap.put("total", pageInfo.getTotal());
        resultVO.setData(dataMap);
        return resultVO;
    }

    /**
     * 获取所有用户分布地址坐标
     *
     * @return
     */
    public List<List<Double>> getAllUserLocations() {
        PageInfo<LoginLog> pageInfo = loginLogDao.query(1, Integer.MAX_VALUE);

        List<LoginLog> list = pageInfo.getList();

        Map<String, Integer> locationMap = new HashMap<>();

        for (LoginLog loginLog : list) {
            BigDecimal pointX = loginLog.getPointX();
            BigDecimal pointY = loginLog.getPointY();
            if (pointX != null && pointY != null) {
                double doubleValueX = pointX.doubleValue();
                double doubleValueY = pointY.doubleValue();
                String key = doubleValueX+"-"+doubleValueY;
                if(locationMap.containsKey(key)){
                    Integer num = locationMap.get(key);
                    locationMap.put(key,++num);
                }else{
                    locationMap.put(key,1);
                }
            }
        }

        List<List<Double>> locationList = new ArrayList<>();

        Set<Map.Entry<String, Integer>> entrySet = locationMap.entrySet();
        for(Map.Entry<String,Integer> entry:entrySet ){
            String key = entry.getKey();
            Integer value = entry.getValue();
            String[] split = key.split("-");
            List<Double> doubleList=new ArrayList<>();
            doubleList.add(Double.parseDouble(split[0]));
            doubleList.add(Double.parseDouble(split[1]));
            doubleList.add(Double.parseDouble(String.valueOf(value)));

            locationList.add(doubleList);
        }

        return locationList;

    }
}
